package service

import (
	"perfect-admin/dao"
	"perfect-admin/model"
	"perfect-admin/model/request"
	"perfect-admin/utils"
)

// 登录验证
func LoginCheck(username string, password string) (user *model.SysUser, msg string, isPass bool) {
	password = utils.Sha256(password)
	user, ok := CheckUserExist(username, password)
	if !ok {
		return user, "用户或密码不正确", false
	}
	return user, "登录成功", true
}

// 验证用户是否存在
func CheckUserExist(username string, password string) (user *model.SysUser, ok bool) {
	user = new(model.SysUser)
	dao.DB.Where(&model.SysUser{Username:username, Password:password, State:true}).Preload("Role").First(&user)
	return user, user.ID > 0
}

func ResetPassword(user_form request.UserForm) (err error) {
	password := utils.Sha256(user_form.Password)
	new_password := utils.Sha256(user_form.NewPassword)
	user := model.SysUser{Username:user_form.Username, Password:password}
	return dao.DB.Model(&model.SysUser{}).Where(&user).Update("password", new_password).Error
}


func GetUserInfoList(queryInfo request.QueryInfo) (users []model.SysUser, total int,  err error) {
	if queryInfo.Query == "" {
		if err = dao.DB.Model(&model.SysUser{}).Count(&total).Error; err != nil{
			return
		}
		err = dao.DB.Limit(queryInfo.PageSize).Offset((queryInfo.PageNum-1)*queryInfo.PageSize).Preload("Role").Find(&users).Error
	}else{
		if err = dao.DB.Model(&model.SysUser{}).Where("username like ?", queryInfo.Query + "%").Count(&total).Error; err != nil{
			return
		}
		err = dao.DB.Where("username like ?", queryInfo.Query + "%").Limit(queryInfo.PageSize).Offset((queryInfo.PageNum-1)*queryInfo.PageSize).Preload("Role").Find(&users).Error
	}
	return
}

func ChangeUserState(user request.StateForm) error {
	return dao.DB.Model(&model.SysUser{}).Where("id = ?", user.ID).Update("state", user.State).Error
}

func UpdateUserRole(user request.UserRoleForm) (err error){
	var role model.SysRole
	err = dao.DB.Where(&model.SysRole{RoleId:user.RoleId}).First(&role).Error
	return dao.DB.Model(&model.SysUser{}).Where("id = ?", user.UserId).Update("role_id", user.RoleId).Error
}

func AddOneUser(user model.SysUser) error {
	user.Role = model.SysRole{}
	user.Password = utils.Sha256("000000")	// 默认密码为000000
	return dao.DB.Create(&user).Error
}

func UpdateUser(user model.SysUser) error {
	user.Role = model.SysRole{}
	return dao.DB.Model(&model.SysUser{}).Where("id = ?", user.ID).Updates(&model.SysUser{Username:user.Username, RoleId:user.RoleId}).Error
}

func DeleteUser(id int) error {
	return dao.DB.Unscoped().Where("id = ?", id).Delete(&model.SysUser{}).Error
}